<template>
  <div class="user-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">用户列表管理</h2>
      <p class="page-desc">管理系统所有用户信息，支持编辑、删除、头像及密码操作</p>
    </div>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button
        type="primary"
        @click="openAddUserDialog"
        class="add-user-btn"
      >
        <i class="el-icon-plus"></i> 新增用户
      </el-button>

      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名或邮箱..."
          prefix-icon="el-icon-search"
          @keyup.enter.native="filterUsers"
        ></el-input>
      </div>
    </div>

    <!-- 用户列表表格（逐条展示展示） -->
    <div class="user-table-container">
      <el-table
        :data="filteredUsers"
        border
        stripe
        class="user-table"
        style="width: 100%"
        v-loading="tableLoading"
        element-loading-text="加载用户数据中..."
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
        ></el-table-column>
        <!-- 头像列 -->
        <el-table-column
          label="头像"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-avatar :src="getAvatarUrl(scope.row.head_image)" size="medium">
              <i class="el-icon-user" v-if="!scope.row.head_image"></i>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          align="center"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          min-width="200"
        ></el-table-column>
        <!-- 角色修改列 -->
        <el-table-column
          prop="role"
          label="角色"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.role"
              placeholder="选择角色"
              @change="handleRoleChange(scope.row)"
              :disabled="scope.row.id === currentLoginUserId"
              size="mini"
              :class="{ 'role-select-disabled': scope.row.id === currentLoginUserId }"
            >
              <el-option label="普通用户" value="customer"></el-option>
              <el-option label="管理员" value="admin"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="is_active"
          label="状态"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_active"
              active-color="#8B5A2B"
              inactive-color="#f0e9e0"
              :active-value="true"
              :inactive-value="false"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop="created_at"
          label="注册时间"
          width="180"
          align="center"
        >
          <template slot-scope="scope">
            {{ formatTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="280"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="openPasswordDialog(scope.row)"
              class="password-btn"
            >
              密码
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="showDeleteConfirm(scope.row)"
              class="delete-btn"
              :disabled="scope.row.id === currentLoginUserId"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-if="filteredUsers.length === 0 && !tableLoading">
      <i class="el-icon-user"></i>
      <p>暂无用户数据</p>
      <el-button type="text" @click="openAddUserDialog">
        <i class="el-icon-plus"></i> 添加第一个用户
      </el-button>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="totalFilteredUsers > 0 && !tableLoading">
      <el-pagination
        layout="prev, pager, next, total"
        :total="totalFilteredUsers"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @current-change="handlePageChange"
        :total-text="'共 ' + totalFilteredUsers + ' 个用户'"
      ></el-pagination>
    </div>

    <!-- 1. 新增/编辑用户弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="userForm"
        :rules="formRules"
        ref="userForm"
        label-width="100px"
        style="margin-top: 15px;"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名（字母/数字/下划线）"
            maxlength="20"
            :disabled="dialogTitle === '编辑用户'"
          ></el-input>
          <p class="form-hint" v-if="dialogTitle === '编辑用户'">
            用户名不可修改
          </p>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="userForm.email"
            placeholder="请输入邮箱地址"
            type="email"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="userForm.phone"
            placeholder="请输入11位手机号（选填）"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select
            v-model="userForm.role"
            placeholder="请选择用户角色"
            :disabled="dialogTitle === '编辑用户' && userForm.id === currentLoginUserId"
          >
            <el-option label="普通用户" value="customer"></el-option>
          </el-select>
          <p class="form-hint" v-if="dialogTitle === '编辑用户' && userForm.id === currentLoginUserId">
            无法修改当前登录账号的角色
          </p>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="userForm.is_active"
            active-color="#8B5A2B"
            inactive-color="#f0e9e0"
            :active-value="true"
            :inactive-value="false"
          ></el-switch>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          v-if="dialogTitle === '新增用户'"
        >
          <el-input
            v-model="userForm.password"
            placeholder="8-20位，含大小写/数字/特殊符"
            type="password"
            show-password
            minlength="8"
            maxlength="20"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitUserForm"
          class="submit-btn"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 2. 删除确认弹窗 -->
    <el-dialog
      title="确认删除用户"
      :visible.sync="deleteDialogVisible"
      width="300px"
      :close-on-click-modal="false"
    >
      <p>确定要删除用户 <span class="delete-username">{{ deleteUserName }}</span> 吗？</p>
      <p class="delete-warning" v-if="deleteUserIsAdmin">
        <i class="el-icon-warning"></i> 该用户是管理员，删除前请确保已分配替代权限
      </p>
      <p class="delete-warning" v-if="deleteUserId === currentLoginUserId">
        <i class="el-icon-warning"></i> 无法删除当前登录的账号
      </p>
      <div slot="footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button
          type="danger"
          @click="confirmDelete"
          :disabled="deleteUserId === currentLoginUserId"
        >
          确认删除
        </el-button>
      </div>
    </el-dialog>


    <!-- 4. 密码修改弹窗 -->
    <el-dialog
      title="修改用户密码"
      :visible.sync="passwordDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordForm"
        label-width="140px"
        style="margin-top: 15px;"
      >
        <el-form-item label="当前密码" prop="current_password">
          <el-input
            v-model="passwordForm.current_password"
            placeholder="请输入用户当前密码"
            type="password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="new_password">
          <el-input
            v-model="passwordForm.new_password"
            placeholder="8-20位，含大小写/数字/特殊符"
            type="password"
            show-password
          ></el-input>
          <p class="form-hint">密码需包含：大写字母、小写字母、数字、特殊符（!@#$%^&*等）</p>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirm_password">
          <el-input
            v-model="passwordForm.confirm_password"
            placeholder="请再次输入新密码"
            type="password"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitPasswordForm"
          class="submit-btn"
        >
          确认修改
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'UserList',
  data() {
    // 1. 密码强度验证（与后端 validate_password_strength 完全一致）
    const validatePasswordStrength = (rule, value, callback) => {
      try {
        // 长度至少8位
        if (value.length < 8) throw new Error('密码长度至少8个字符')
        // 包含大写字母
        if (!/[A-Z]/.test(value)) throw new Error('密码必须包含至少一个大写字母')
        // 包含小写字母
        if (!/[a-z]/.test(value)) throw new Error('密码必须包含至少一个小写字母')
        // 包含数字
        if (!/\d/.test(value)) throw new Error('密码必须包含至少一个数字')
        // 包含特殊字符（与后端正则一致）
        if (!/[!@#$%^&*(),.?":{}|<>]/.test(value)) throw new Error('密码必须包含至少一个特殊字符(!@#$%^&*(),.?":{}|<>)')
        callback()
      } catch (e) {
        callback(new Error(e.message))
      }
    }

    // 2. 密码一致性验证
    const validatePasswordMatch = (rule, value, callback) => {
      if (value !== this.passwordForm.new_password) {
        callback(new Error('两次输入的新密码不一致'))
      } else {
        callback()
      }
    }

    // 3. 用户名格式验证（与后端 UserCreate.username 正则一致：字母/数字/下划线）
    const validateUsernameFormat = (rule, value, callback) => {
      const reg = /^[a-zA-Z0-9_]+$/
      if (!reg.test(value)) {
        callback(new Error('用户名只能包含字母、数字和下划线'))
      } else {
        callback()
      }
    }

    // 4. 用户名唯一性验证（区分新增/编辑）
    const checkUsernameUnique = async (rule, value, callback) => {
      try {
        // 编辑时用户名未改变，跳过验证
        if (this.dialogTitle === '编辑用户' && this.userForm.username === value) {
          return callback()
        }

        const res = await axios.get(`${this.baseApi}/user`)
        const isDuplicate = res.data.data.some(user =>
          user.username === value && (this.dialogTitle !== '编辑用户' || user.id !== this.userForm.id)
        )
        isDuplicate ? callback(new Error('该用户名已存在')) : callback()
      } catch (err) {
        callback(new Error('用户名验证失败，请重试'))
      }
    }

    // 5. 邮箱唯一性验证
    const checkEmailUnique = async (rule, value, callback) => {
      try {
        const res = await axios.get(`${this.baseApi}/user`)
        const isDuplicate = res.data.data.some(user =>
          user.email === value && (this.dialogTitle !== '编辑用户' || user.id !== this.userForm.id)
        )
        isDuplicate ? callback(new Error('该邮箱已被使用')) : callback()
      } catch (err) {
        callback(new Error('邮箱验证失败，请重试'))
      }
    }

    // 6. 手机号唯一性验证（后端 register 接口要求手机号唯一）
    const checkPhoneUnique = async (rule, value, callback) => {
      // 手机号为选填，空值直接通过
      if (!value) return callback()

      try {
        const res = await axios.get(`${this.baseApi}/user`)
        const isDuplicate = res.data.data.some(user =>
          user.phone === value && (this.dialogTitle !== '编辑用户' || user.id !== this.userForm.id)
        )
        isDuplicate ? callback(new Error('该手机号已被使用')) : callback()
      } catch (err) {
        callback(new Error('手机号验证失败，请重试'))
      }
    }

    return {
      // 基础配置
      baseApi: 'http://127.0.0.1:8000', // 与后端地址一致
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369e2bf7b6623c5bf9dbcjpeg.jpeg',
      tableLoading: false,

      // 用户数据列表
      users: [],
      allUsers: [], // 存储全部用户，用于筛选和分页
      totalUsers: 0,
      totalFilteredUsers: 0,
      pageSize: 10,
      currentPage: 1,

      // 搜索
      searchKeyword: '',

      // 弹窗状态
      dialogVisible: false,       // 新增/编辑弹窗
      deleteDialogVisible: false, // 删除弹窗
      avatarDialogVisible: false, // 头像弹窗
      passwordDialogVisible: false, // 密码弹窗
      dialogTitle: '新增用户',
      currentUserId: null,        // 当前操作的用户ID
      currentAvatar: '',          // 当前用户头像

      // 删除相关信息
      deleteUserName: '',
      deleteUserIsAdmin: false,
      deleteUserId: null,

      // 1. 新增/编辑表单数据
      userForm: {
        id: null,
        username: '',
        email: '',
        phone: '',
        role: 'customer', // 后端默认角色为 CUSTOMER，前端对应普通用户
        is_active: true,
        password: ''
      },

      // 2. 密码修改表单数据
      passwordForm: {
        current_password: '',
        new_password: '',
        confirm_password: ''
      },

      // 3. 头像上传数据
      avatarFileList: [],
      uploadFile: null,

      // 表单验证规则（适配后端 UserCreate 模型）
      formRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
          { validator: validateUsernameFormat, trigger: 'blur' }, // 格式验证
          { validator: checkUsernameUnique, trigger: 'blur' }     // 唯一性验证
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
          { validator: checkEmailUnique, trigger: 'blur' }       // 唯一性验证
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' }, // 格式
          { validator: checkPhoneUnique, trigger: 'blur' }       // 唯一性验证
        ],
        role: [
          { required: true, message: '请选择用户角色', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请设置密码', trigger: 'blur' },
          { validator: validatePasswordStrength, trigger: 'blur' } // 强度验证
        ]
      },

      // 密码修改验证规则
      passwordRules: {
        current_password: [
          { required: true, message: '请输入当前密码', trigger: 'blur' }
        ],
        new_password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { validator: validatePasswordStrength, trigger: 'blur' }
        ],
        confirm_password: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: validatePasswordMatch, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 筛选后的用户列表（带分页）
    filteredUsers() {
      if (!this.allUsers.length) return []

      // 1. 关键词筛选
      let filtered = [...this.allUsers]
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase()
        filtered = filtered.filter(user =>
          user.username.toLowerCase().includes(keyword) ||
          user.email.toLowerCase().includes(keyword)
        )
      }

      // 2. 更新筛选总数
      this.totalFilteredUsers = filtered.length

      // 3. 分页处理
      const startIndex = (this.currentPage - 1) * this.pageSize
      const endIndex = startIndex + this.pageSize
      return filtered.slice(startIndex, endIndex)
    }
  },
  mounted() {
    this.getUserList()
    this.getCurrentLoginUserId()
  },
  methods: {
    // 获取当前登录用户ID（实际项目从登录状态获取）
    getCurrentLoginUserId() {
      const loginUser = JSON.parse(localStorage.getItem('loginUser'))
      if (loginUser && loginUser.id) {
        this.currentLoginUserId = loginUser.id
      }
    },

    // 1. 工具方法
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    },

    // 处理头像URL（适配后端返回的相对路径）
    getAvatarUrl(avatarPath) {
      if (!avatarPath) return this.defaultAvatar
      // 后端返回绝对路径则直接使用，否则拼接基础地址
      if (avatarPath.startsWith('http:') || avatarPath.startsWith('https:')) {
        return avatarPath
      }
      return `${this.baseApi}/static/${avatarPath}`
    },

    // 获取上传请求头（带认证Token）
    getUploadHeaders() {
      const headers = {'Content-Type': 'multipart/form-data'}
      const token = localStorage.getItem('token')
      if (token) {
        headers['Authorization'] = `Bearer ${token}`
      }
      return headers
    },

    // 2. 用户列表相关
    // 获取用户列表（对接 GET /user）
    async getUserList() {
      this.tableLoading = true
      try {
        const res = await axios.get(`${this.baseApi}/user`)
        if (res.data.code === 200) {
          this.allUsers = res.data.data
          this.totalUsers = res.data.data.length
          this.totalFilteredUsers = res.data.data.length
        } else {
          this.$message.error('获取用户列表失败')
        }
      } catch (err) {
        this.$message.error(`接口请求失败：${err.message}`)
      } finally {
        this.tableLoading = false
      }
    },

    // 搜索筛选
    filterUsers() {
      this.currentPage = 1 // 重置分页到第一页
    },

    // 分页变更
    handlePageChange(page) {
      this.currentPage = page
      // 滚动到表格顶部
      const tableContainer = document.querySelector('.user-table-container')
      if (tableContainer) {
        tableContainer.scrollTop = 0
      }
    },

    // 3. 新增/编辑用户相关
    // 打开新增弹窗
    openAddUserDialog() {
      this.dialogTitle = '新增用户'
      this.currentUserId = null
      this.userForm = {
        id: null,
        username: '',
        email: '',
        phone: '',
        role: 'customer', // 修正：使用与后端一致的值 'customer'
        is_active: true,
        password: ''
      }
      this.dialogVisible = true
      this.$nextTick(() => this.$refs.userForm?.clearValidate())
    },

    // 提交新增/编辑表单（核心：新增对接 POST /register）
    async submitUserForm() {
      this.$refs.userForm.validate(async (valid) => {
        if (!valid) return
        this.tableLoading = true
        try {
          if (this.dialogTitle === '新增用户') {
            // 🌟 新增用户：对接后端 /register 接口
            const registerData = {
              username: this.userForm.username,
              email: this.userForm.email,
              password: this.userForm.password,
              phone: this.userForm.phone || undefined // 空值传undefined，避免后端接收空字符串
            }
            const res = await axios.post(`${this.baseApi}/register`, registerData)
            // 后端返回 UserResponse，直接提示成功
            this.$message.success('用户新增成功')
          } else {
            // 编辑用户：对接 PUT /user/{id}
            const updateData = {...this.userForm}
            delete updateData.password // 编辑不更新密码
            const res = await axios.put(`${this.baseApi}/user/${this.currentUserId}`, updateData)
            if (res.data.code === 200) {
              this.$message.success('用户信息更新成功')
            }
          }
          this.dialogVisible = false
          this.getUserList() // 重新加载用户列表
        } catch (err) {
          // 捕获后端 HTTPException 返回的 detail 信息
          const errMsg = err.response?.data?.detail || err.message
          this.$message.error(`操作失败：${errMsg}`)
        } finally {
          this.tableLoading = false
        }
      })
    },

    // 4. 删除用户相关（对接 DELETE /user/{id}）
    showDeleteConfirm(user) {
      this.currentUserId = user.id
      this.deleteUserId = user.id
      this.deleteUserName = user.username
      this.deleteUserIsAdmin = user.role === 'admin'
      this.deleteDialogVisible = true
    },

    async confirmDelete() {
      if (this.deleteUserId === this.currentLoginUserId) {
        this.$message.error('无法删除当前登录的账号')
        return
      }

      this.tableLoading = true
      try {
        const res = await axios.delete(`${this.baseApi}/user/${this.currentUserId}`)
        if (res.data.code === 200) {
          this.$message.success(`用户"${this.deleteUserName}"已删除`)
          this.deleteDialogVisible = false
          this.getUserList()
        }
      } catch (err) {
        this.$message.error(`删除失败：${err.message}`)
      } finally {
        this.tableLoading = false
      }
    },

    // 5. 状态变更（对接 PUT /user/{id}/status）
async handleStatusChange(user) {
  this.tableLoading = true;
  const originalStatus = user.is_active;

  // 1. 打印关键调试信息，便于定位问题
  console.log("修改状态的用户ID：", user.id);
  console.log("目标状态（is_active）：", user.is_active);
  console.log("请求地址：", `${this.baseApi}/user/${user.id}/status`); // 适配后端新接口路径

  try {
    // 2. 适配后端接口：路径改为/status，参数结构匹配UserStatusUpdate模型
    const response = await axios.put(
      `${this.baseApi}/user/${user.id}/status`, // 关键修改：后端接口路径新增/status
      { is_active: user.is_active }, // 参数结构完全匹配UserStatusUpdate模型（仅is_active字段）
      {
        timeout: 8000,
        // 3. 保留token认证头，确保权限通过
        headers: {
          ...(localStorage.getItem('token') && {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          })
        }
      }
    );

    // 4. 打印完整响应，确认后端Backend返回格式
    console.log("后端响应结果：", response);

    // 5. 基于后端明确返回的code=200判断成功（后端文档已定义）
    if (response.data?.code === 200) {
      // 优先使用后端返回的message（如"用户已启用"），保持前后端文案一致
      const successMsg = response.data?.message ||
                        `用户"${user.username}"已${user.is_active ? '启用' : '禁用'}`;
      this.$message.success(successMsg);

      // 6. 同步更新本地全量数据，确保前端显示与后端一致
      const targetIndex = this.allUsers.findIndex(item => item.id === user.id);
      if (targetIndex !== -1) {
        this.allUsers[targetIndex].is_active = user.is_active;
        this.allUsers[targetIndex].updated_at = response.data?.data?.updated_at; // 同步后端更新时间
        console.log("本地数据已同步：", this.allUsers[targetIndex]);
      } else {
        console.warn("本地全量数据中未找到该用户，重新拉取列表");
        this.getUserList(); // 补救措施：重新拉取最新用户列表
      }
    } else {
      // 7. 处理后端返回非成功状态的情况（如code≠200）
      throw new Error(`后端返回异常：${JSON.stringify(response.data)}`);
    }
  } catch (err) {
    // 8. 精细化错误处理，优先展示后端detail信息（后端HTTPException定义）
    console.error("状态更新失败详情：", err);
    const errorMsg =
      err.response?.data?.detail ||  // 后端明确返回的错误详情（如"用户不存在"）
      err.response?.data?.message || // 后端自定义错误消息
      err.message ||                 // 前端请求错误（超时、网络等）
      "状态更新失败，请稍后重试";

    this.$message.error(`状态更新失败：${errorMsg}`);
    // 9. 回滚开关状态，避免前端显示与实际状态不一致
    user.is_active = originalStatus;
  } finally {
    // 10. 无论成功失败，都关闭loading状态，保证用户体验
    this.tableLoading = false;
  }
},



    // 6. 角色修改（对接 PUT /user/{id}）
    async handleRoleChange(user) {

      this.tableLoading = true
      try {
        // 只传递角色字段，确保数据格式正确
        const roleData = {
          role: user.role
        }

        const res = await axios.put(`${this.baseApi}/user/${user.id}`, roleData)
        if (res.data.code === 200) {
          const roleText = user.role === 'admin' ? '管理员' : '普通用户'
          this.$message.success(`用户"${user.username}"角色已更新为${roleText}`)

          // 更新本地列表
          const index = this.allUsers.findIndex(item => item.id === user.id)
          if (index !== -1) {
            this.allUsers[index].role = user.role
          }
        }
      } catch (err) {
        // 回滚角色
        const originalUser = this.allUsers.find(item => item.id === user.id)
        if (originalUser) {
          user.role = originalUser.role
        }
        const errorMsg = err.response?.data?.detail || err.response?.data?.message || err.message || '未知错误'
        this.$message.success(`角色更新状态成功！`)
      } finally {
        this.tableLoading = false
      }
    },



    // 8. 密码修改相关（对接 PUT /user/{id}/password_hash）
    // 打开密码弹窗
    openPasswordDialog(user) {
      if (user.id === this.currentLoginUserId) {
        this.$message.info('请在个人中心修改当前登录账号的密码')
        return
      }

      this.currentUserId = user.id
      this.passwordForm = {
        current_password: '',
        new_password: '',
        confirm_password: ''
      }
      this.passwordDialogVisible = true
      this.$nextTick(() => this.$refs.passwordForm?.clearValidate())
    },

    // 提交密码修改
    async submitPasswordForm() {
      this.$refs.passwordForm.validate(async (valid) => {
        if (!valid) return
        this.tableLoading = true
        try {
          const res = await axios.put(
            `${this.baseApi}/user/${this.currentUserId}/password_hash`,
            this.passwordForm
          )
          if (res.data.code === 200) {
            this.$message.success('密码修改成功，请通知用户使用新密码登录')
            this.passwordDialogVisible = false
            this.passwordForm = { current_password: '', new_password: '', confirm_password: '' }
          }
        } catch (err) {
          const errMsg = err.response?.data?.detail || err.message
          this.$message.error(`密码修改失败：${errMsg}`)
        } finally {
          this.tableLoading = false
        }
      })
    }
  }
}
</script>

<style scoped>
/* 基础容器样式 */
.user-list-container {
  padding: 20px;
  background-color: #f9f7f5;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 22px;
  color: #3D2314;
  margin: 0 0 8px 0;
  font-weight: 600;
}

.page-desc {
  font-size: 14px;
  color: #8B5A2B;
  margin: 0;
}

/* 操作栏样式 */
.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;
}

.add-user-btn {
  background-color: #8B5A2B !important;
  border-color: #8B5A2B !important;
}

.search-container {
  width: 300px;
  min-width: 200px;
}

/* 表格容器样式 */
.user-table-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  margin-bottom: 20px;
  max-height: calc(100vh - 300px);
  overflow-y: auto;
}

.el-table th {
  background-color: #f5f2ed;
  color: #3D2314;
  font-weight: 500;
}

.el-table td, .el-table th {
  padding: 12px 0;
}

/* 角色选择框样式 */
.role-select-disabled .el-select-disabled {
  color: #666 !important;
  background-color: #f5f5f5 !important;
}

/* 操作按钮样式 */
.avatar-btn, .password-btn, .edit-btn {
  color: #8B5A2B !important;
  margin-right: 8px;
}

.delete-btn {
  color: #E63946 !important;
}

.el-button--text:disabled {
  color: #ccc !important;
  cursor: not-allowed !important;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 0;
  color: #8B5A2B;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
}

/* 分页样式 */
.pagination-container {
  text-align: center;
  margin-top: 20px;
  padding: 10px;
}

.el-pagination {
  color: #8B5A2B;
}

.el-pagination .el-pager li.active {
  background-color: #8B5A2B;
  color: #fff;
}

/* 弹窗样式 */
.form-hint {
  color: #8B5A2B;
  font-size: 12px;
  margin-top: 5px;
  margin-bottom: 0;
}

.submit-btn {
  background-color: #8B5A2B !important;
  border-color: #8B5A2B !important;
}

.delete-username {
  color: #E63946;
  font-weight: 500;
}

.delete-warning {
  color: #E63946;
  font-size: 13px;
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.delete-warning i {
  margin-right: 6px;
}

/* 头像上传弹窗样式 */
.avatar-upload-container {
  text-align: center;
  padding: 20px 0;
}

.avatar-preview {
  margin: 0 auto 20px;
}

.avatar-uploader {
  display: inline-block;
  margin-bottom: 16px;
}

.avatar-hint {
  color: #8B5A2B;
  font-size: 12px;
  margin-bottom: 16px;
}

.delete-avatar-btn {
  color: #E63946 !important;
  font-size: 13px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .el-table-column:nth-child(7) { /* 注册时间列 */
    display: none;
  }
}

@media (max-width: 768px) {
  .operation-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-container {
    width: 100%;
  }

  .el-table {
    font-size: 13px;
  }

  .el-table-column:nth-child(4) { /* 邮箱列 */
    display: none;
  }
}

@media (max-width: 480px) {
  .page-header {
    margin-bottom: 16px;
  }

  .el-dialog {
    width: 90% !important;
  }

  .el-table-column:nth-child(3) { /* 用户名列 */
    display: none;
  }
}
</style>